#!/bin/bash

# 参数处理
v_f_this="$0"
v_args=("$@")
v_index=0

# 源文件
v_f_source=""
# 目标文件
v_f_target=""
# map声明
declare -A v_map=()

# 遍历参数
while [ ${v_index} -lt ${#v_args[@]} ]; do
    v_arg=${v_args[$v_index]}

    if [ "$v_arg" == "-s" ]; then
        v_index=`expr ${v_index} + 1`
        v_f_source=${v_args[$v_index]}
        v_index=`expr ${v_index} + 1`
        continue
    fi

    if [ "$v_arg" == "-t" ]; then
        v_index=`expr ${v_index} + 1`
        v_f_target=${v_args[$v_index]}
        v_index=`expr ${v_index} + 1`
        continue
    fi

    if [[ "$v_arg"=~"=" ]]; then
        v_key=`echo "$v_arg" | cut -d "=" -f 1`
        v_value=`echo "$v_arg" | cut -d "=" -f 2`
        v_map["$v_key"]=${v_value}
        v_index=`expr ${v_index} + 1`
        continue
    fi
    echo "Error: arguments format: $v_f_this -s /path/to/source-file -t /path/to/target-file [var...n=value...n]"
    exit -1
done

if [ ! -f "$v_f_source" ]; then
    echo "Error: source file does not exist : $v_f_source"
    echo "Error: arguments format: $v_f_this -s /path/to/source-file -t /path/to/target-file [var...n=value...n]"
    exit -1
fi

if [ ! -f "$v_f_target" ]; then
    echo "Error: target file does not exist"
    echo "Error: arguments format: $v_f_this -s /path/to/source-file -t /path/to/target-file [var...n=value...n]"
    exit -1
fi

v_f_timeN=`date "+%N"`
cp -rf "$v_f_source" "$v_f_timeN"

for key in ${!v_map[@]}
do
    echo "$key -> ${v_map[$key]}"
    # / -> \/ 路径转义
    v_replace_content=`echo ${v_map[$key]} | sed 's#\/#\\\/#g'`
    sed -i "s/\${$key}/$v_replace_content/g" "$v_f_timeN"
done

cp -rf "$v_f_timeN" "$v_f_target"
rm -f "$v_f_timeN"

exit -1


